import { defineStore } from 'pinia'
import { ElLoading } from 'element-plus'
import {
  setToken as updateToken,
  getToken,
  setUser,
  getUser,
  removeToken,
  removeUser,
} from '@/app/storage'
import { LOGIN_NAME, REDIRECT_HOME_PATH } from '@/const/router'
import { USER_STORE_NAME } from '../const'
import useAuthStore from './auth'
import router from '@/router'

export default defineStore(USER_STORE_NAME, () => {
  const authStore = useAuthStore()

  const token = ref(getToken() || null)
  const userInfo = ref(getUser() || null)

  function setToken(value) {
    token.value = value
    updateToken(value)
  }

  function setUserInfo(value) {
    userInfo.value = value
    setUser(value)
  }

  function logout() {
    token.value = null
    userInfo.value = null
    // FIXME: 解决退出登录后再次登录跳转404问题
    authStore.clearAuthMenuList()
    removeToken()
    removeUser()
    setTimeout(() => router.replace(`/${LOGIN_NAME}`), 500)
  }

  async function login(data) {
    const instance = ElLoading.service({
      lock: true,
      text: '登录中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    data.isRemember && (await setToken(new Date().getTime()))
    await setUserInfo(data)
    await instance.close()
    router.push(REDIRECT_HOME_PATH)
  }

  return {
    token,
    userInfo,
    setToken,
    setUserInfo,
    logout,
    login,
  }
})
